from selenium import webdriver
from selenium.webdriver.common.by import By

# 使用浏览器驱动，自动启动浏览器
driver = webdriver.Chrome()
# 浏览器最大化
# driver.maximize_window()
driver.minimize_window()

# 访问百度
driver.get('https://www.baidu.com')
print(driver.current_url)  # 打印url
# print(driver.page_source)  # 打印网页html

for i in driver.get_cookies():  # 打印cookies
    # print(i)
    pass

a = driver.execute_script(
    """
    console.log('00aa');
    return localStorage.getItem('app_id');
    """)
print(a)

# 定位搜索框元素
# search_box = driver.find_element(By.ID, 'kw')
search_box = driver.find_element('xpath', '//*[@id="kw"]')
print(search_box.text)
search_box.screenshot("a.png")  # 将元素截图并保存
print(search_box.rect)  # 打印该元素大小以及位置信息
print(search_box.tag_name)  # 元素属性
# 搜索框输入hello world
search_box.send_keys('hello world')
search_box.clear()  # 清空
search_box.send_keys('123')

# 定位搜索按钮元素
search_button = driver.find_element(By.ID, 'su')
# 点击搜索按钮
search_button.click()

# 等待页面加载稳定，可根据实际情况调整等待时间
import time

time.sleep(2)

print(driver.title)  # 打印标题

# print(driver.get_screenshot_as_base64())
# print(driver.get_screenshot_as_png())
# print(driver.get_screenshot_as_file("aaa.png"))

# 截图保存，指定保存的文件路径和文件名
screenshot_path = '../data/baidu.png'
driver.save_screenshot(screenshot_path)
driver.get_screenshot_as_file(screenshot_path)
print(f"截图已保存到 {screenshot_path}")

# 等待你输入任意内容后按回车键，然后关闭浏览器
# input("按回车键关闭浏览器...")
driver.quit()
